   package com.javalong.affairs.module.notifything.activity;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.debby.MyFileManager;
import com.google.gson.reflect.TypeToken;
import com.javalong.affairs.R;
import com.javalong.affairs.base.activity.UIHandlerActivity;
import com.javalong.affairs.base.common.ServiceLocator;
import com.javalong.affairs.base.common.UIHandler;
import com.javalong.affairs.base.constant.BundleKey;
import com.javalong.affairs.base.constant.RequestCode;
import com.javalong.affairs.base.constant.RequestKey;
import com.javalong.affairs.base.data.AllData;
import com.javalong.affairs.base.listener.BaseResponseListener;
import com.javalong.affairs.base.listener.MultipartRequest;
import com.javalong.affairs.base.manager.IntentManager;
import com.javalong.affairs.base.model.User;
import com.javalong.affairs.base.multirequest.MultipartRequestParams;
import com.javalong.affairs.base.ui.TextSelectView;
import com.javalong.affairs.base.ui.TextSelectView.OnImageClick;
import com.javalong.affairs.base.ui.TopTitle;
import com.javalong.affairs.base.utils.DateTimePickDialogUtil;
import com.javalong.affairs.base.utils.DateUtils;
import com.javalong.affairs.base.utils.HttpUtils;
import com.javalong.affairs.base.utils.StringUtils;
import com.javalong.affairs.base.utils.ToastUtils;
import com.javalong.affairs.base.utils.UrlUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

@ContentView(R.layout.activity_sendmsg)
public class SendMsgActivity extends UIHandlerActivity implements OnImageClick {

	@ViewInject(R.id.ui_toptitle)
	private TopTitle topTitle;
	@ViewInject(R.id.tv_time)
	private TextView tv_time;
	@ViewInject(R.id.et_address)
	private EditText et_address;
	@ViewInject(R.id.et_content)
	private EditText et_content;
	@ViewInject(R.id.bt_send)
	private Button bt_send;
	@ViewInject(R.id.ui_tsview_receiver)
	private TextSelectView tsView_receiver;
	@ViewInject(R.id.et_title)
	private EditText et_title;
	@ViewInject(R.id.bt_settime)
	private Button bt_settime;
	@ViewInject(R.id.et_timelimit)
	private EditText et_timelimit;
	@ViewInject(R.id.ui_tsview_file)
	private TextSelectView ui_tsview_file;
	@ViewInject(R.id.ui_tsview_examiner)
	private TextSelectView ui_tsview_examiner;
	@ViewInject(R.id.tv_sender)
	private TextView tv_sender;
	private Date nowDate;
	private StringBuilder receiverStr = new StringBuilder();
	private StringBuilder examinerStr = new StringBuilder();
	private File currFile;
	private DateTimePickDialogUtil timeDialog;
	@ViewInject(R.id.sp_type)
	private Spinner sp_type;
	private int messageType=1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		topTitle.setOnLeftDrawableClick(this);
		nowDate = new Date();
		User user = (User) AllData.GetInstance().get(
				R.string.data_user_current_user);
		tv_sender.setText(user.name);
		initUI();
		initData();
	}

	private void initData() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,
				new String[] { "通知", "文件" });
		sp_type.setAdapter(adapter);
		sp_type.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				if(position==0){messageType=1;}else{
					messageType=2;
				}
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}

	private void initUI() {
		tsView_receiver.setOnImageClick(this);
		bt_send.setOnClickListener(this);
		tv_time.setText(DateUtils.formatDate(nowDate));
		bt_settime.setOnClickListener(this);
		ui_tsview_file.setOnImageClick(this);
		ui_tsview_examiner.setOnImageClick(this);
		et_content.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		Bundle bundle = null;
		switch (view.getId()) {
		case R.id.ui_tsview_receiver:
			bundle = new Bundle();
			bundle.putInt("type", 0);
			IntentManager.doActivityForResult(SendMsgActivity.this,
					ReceiverActivity.class, RequestCode.RECEIVER, bundle);
			break;
		case R.id.ui_tsview_examiner:
			bundle = new Bundle();
			bundle.putInt("type", 1);
			IntentManager.doActivityForResult(SendMsgActivity.this,
					ReceiverActivity.class, RequestCode.EXAMINER, bundle);
			break;
		case R.id.ui_tsview_file:
			IntentManager.doActivityForResult(SendMsgActivity.this,
					MyFileManager.class, RequestCode.ADD_FILE);
			break;
		case R.id.bt_settime:
			timeDialog = new DateTimePickDialogUtil(this,
					DateUtils.formatDate(nowDate));
			timeDialog.dateTimePicKDialog(tv_time);
			break;
		case R.id.bt_send:
			if (!checkSelected()) {
				return;
			}
			bt_send.setEnabled(false);
			bt_send.setText("正在发送中...");
			User user = (User) AllData.GetInstance().get(
					R.string.data_user_current_user);
			String url = UrlUtils.getUrl("SendMessage", "insert");
			if (currFile != null) {
				MultipartRequestParams param = new MultipartRequestParams();
				param.put(RequestKey.ATTACHMENT, currFile);
				param.put(RequestKey.MESSAGEDATA, et_content.getText()
						.toString().toString());
				param.put(RequestKey.TITLE, et_title.getText().toString());
				param.put(RequestKey.TIME, DateUtils.getTime(nowDate) + "");
				param.put(RequestKey.PLACE, et_address.getText().toString());
				param.put(RequestKey.SENDER, user.userName);
				param.put(RequestKey.RECIPIENT, receiverStr.toString());
				param.put(RequestKey.AUDIT, examinerStr.toString());
				param.put(RequestKey.MESSAGETYPE, messageType+"");
				param.put(RequestKey.TIMELIMIT, et_timelimit.getText()
						.toString());
				HttpUtils.addReuqest(new MultipartRequest(url, param,
						new BaseResponseListener(new TypeToken<User>() {
						}.getType()) {
							@Override
							public void onSuccess(Object obj) {
								super.onSuccess(obj);
								ServiceLocator
										.GetInstance()
										.getInstance(UIHandler.class)
										.postCallback(
												R.string.event_refresh_notification_send,
												null);
								finish();
							}
						}));
			} else {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put(RequestKey.MESSAGEDATA, et_content.getText()
						.toString().toString());
				param.put(RequestKey.TITLE, et_title.getText().toString());
				if (timeDialog != null) {
					param.put(RequestKey.TIME, timeDialog.getSeconds());
				} else {
					param.put(RequestKey.TIME, nowDate.getTime() / 1000);
				}
				param.put(RequestKey.PLACE, et_address.getText().toString());
				param.put(RequestKey.SENDER, user.userName);
				param.put(RequestKey.RECIPIENT, receiverStr.toString());
				param.put(RequestKey.AUDIT, examinerStr.toString());
				param.put(RequestKey.MESSAGETYPE, messageType);
				param.put(RequestKey.TIMELIMIT, et_timelimit.getText()
						.toString());
				HttpUtils.post(url, param, new BaseResponseListener(
						new TypeToken<User>() {
						}.getType()) {
					@Override
					public void onSuccess(Object obj) {
						super.onSuccess(obj);
						ServiceLocator
								.GetInstance()
								.getInstance(UIHandler.class)
								.postCallback(
										R.string.event_refresh_notification_send,
										null);
						finish();
					}
				});
			}

			break;
		case R.id.et_content:
			bundle = new Bundle();
			bundle.putString(BundleKey.EDITCONTENT, et_content.getText()
					.toString());
			IntentManager.doActivityForResult(this, EditContentActivity.class,
					RequestCode.EDITCONTENT, bundle);
			break;
		default:
			break;
		}
	}

	// 判断是否已选
	private boolean checkSelected() {
		if (StringUtils.isEmpty(receiverStr.toString())) {
			ToastUtils.showMessage("请选择接收人");
			return false;
		}
		if (StringUtils.isEmpty(examinerStr.toString())) {
			ToastUtils.showMessage("请选择审核人");
			return false;
		}
		if (StringUtils.isEmpty(et_title.getText().toString())) {
			ToastUtils.showMessage("请输入标题");
			return false;
		}
		/*
		 * if (StringUtils.isEmpty(et_content.getText().toString())) {
		 * ToastUtils.showMessage("请输入内容"); return false; }
		 */
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case RequestCode.RECEIVER:
				receiverStr = new StringBuilder();
				List<User> userList = (List<User>) data
						.getSerializableExtra(BundleKey.USERLIST);
				StringBuilder sb = new StringBuilder();
				for (User u : userList) {
					sb.append(u.userName).append(";");
					receiverStr.append(u.userName).append(",");
				}
				if (receiverStr.toString().endsWith(",")) {
					receiverStr.deleteCharAt(receiverStr.length() - 1);
				}
				if (sb.toString().endsWith(";")) {
					sb.deleteCharAt(sb.length() - 1);
				}
				tsView_receiver.setText(sb.toString());
				break;
			case RequestCode.ADD_FILE:
				String file = data.getStringExtra("file");
				currFile = new File(file);
				if (!currFile.exists() || currFile.isDirectory()) {
					currFile = null;
					ToastUtils.showMessage("上传文件类型错误");
				} else {
					ui_tsview_file.setText("选择文件为：" + file);
				}
				break;
			case RequestCode.EXAMINER:
				examinerStr = new StringBuilder();
				List<User> examinerList = (List<User>) data
						.getSerializableExtra(BundleKey.USERLIST);
				StringBuilder exsb = new StringBuilder();
				for (User u : examinerList) {
					exsb.append(u.userName).append(";");
					examinerStr.append(u.userName).append(",");
				}
				if (examinerStr.toString().endsWith(",")) {
					examinerStr.deleteCharAt(examinerStr.length() - 1);
				}
				if (exsb.toString().endsWith(",")) {
					exsb.deleteCharAt(exsb.length() - 1);
				}
				ui_tsview_examiner.setText(exsb.toString());
				break;
			case RequestCode.EDITCONTENT:
				String editContent = data.getStringExtra(BundleKey.EDITCONTENT);
				et_content.setText(editContent);
				break;
			}
		}
	}
}
